<template>
  <div class="no-background-container">
    <header-component />
    <!-- <el-affix :offset="62">
      <div class="qs-y-table-header">
        <div class="header-label">
          <div class="header-label-title">
            {{ routeName }}
          </div>
        </div>
      </div>
    </el-affix> -->
    <div style="height: 57px"></div>

    <div class="meeting-rooms-overview-content">
      <!-- 统计卡片 -->
      <stats-panel :stats="roomStats" />

      <!-- 在这里增加searchFormQvil -->
      <search-form-qvil v-model="searchParams" :fields="searchFields" :loading="loading" @reset="handleReset" @search="handleSearch">
        <template #actions>
          <el-radio-group v-model="currentView" size="default">
            <el-radio-button label="list">列表视图</el-radio-button>
            <el-radio-button label="timeline">时间轴视图</el-radio-button>
          </el-radio-group>
        </template>
      </search-form-qvil>

      <!-- 列表视图 -->
      <room-list-view
        v-if="currentView === 'list'"
        :current-date="currentDate"
        :loading="loading"
        :rooms="roomList"
        @book-room="handleBookRoom"
        @view-detail="handleViewRoomDetail"
      />

      <!-- 时间轴视图 -->
      <timeline-view
        v-else
        :current-date="currentDate"
        :loading="loading"
        :rooms="roomList"
        :selected-room-id="selectedRoomId"
        @activity-click="(activity) => handleActivityClick(activity)"
        @room-select="handleRoomSelect"
      />

      <!-- 会议室详情弹窗 -->
      <room-detail-dialog v-model="showRoomDetail" :current-date="currentDate" :room="selectedRoom" @book="handleBookRoom" />
    </div>
  </div>
</template>

<script lang="ts" setup>
// import CompanyHeader from '/@/components/common/CompanyHeader.vue'
// import { useUserStore } from '/@/stores/user'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import HeaderComponent from '../components/header.vue'
import { ROOM_STATUS } from '../meetingRooms-new/config'
import RoomDetailDialog from './components/RoomDetailDialog.vue'
import RoomListView from './components/RoomListView.vue'
import StatsPanel from './components/StatsPanel.vue'
import TimelineView from './components/TimelineView.vue'
import { getListApi } from '/@/api/meetingRooms'
import type { ActivityInfo, MeetingRoom } from '/@/types/api'
import request from '/@/utils/request'

// 定义搜索表单字段类型
export interface Field {
  label: string
  prop: string
  component: 'input' | 'select'
  placeholder?: string
  multiple?: boolean
  filterable?: boolean
  options?: Array<{
    label: string
    value: string | number
  }>
  componentProps?: Record<string, any>
}

const router = useRouter()

// 当前视图（列表/时间轴）
const currentView = ref('list')

// 选中的会议室ID
const selectedRoomId = ref<number | null>(null)

// 加载状态
const loading = ref(false)

// 会议室列表
const roomList = ref<MeetingRoom[]>([])

// 选中的会议室
const selectedRoom = ref<MeetingRoom | null>(null)

// 显示会议室详情
const showRoomDetail = ref(false)

// 当前选择的日期
const currentDate = ref(dayjs().format('YYYY-MM-DD'))

// 当前筛选条件
const filterParams = ref({
  location: '',
  date: dayjs().format('YYYY-MM-DD'),
})

// 会议室统计数据
const roomStats = computed(() => ({
  totalRooms: roomList.value.length,
  freeRooms: roomList.value.filter((room) => !isRoomInUse(room)).length,
  inUseRooms: roomList.value.filter((room) => isRoomInUse(room)).length,
  bookingsToday: getBookingsCount(),
}))

// 获取会议总数
const getBookingsCount = () => {
  let count = 0
  roomList.value.forEach((room) => {
    if (room.activityInfos && room.activityInfos.length > 0) {
      count += room.activityInfos.length
    }
  })
  return count
}

// 检查会议室是否被使用中
const isRoomInUse = (room: MeetingRoom) => {
  if (!room.activityInfos || room.activityInfos.length === 0) {
    return false
  }

  // 如果不是今天，永远返回未使用
  if (currentDate.value !== dayjs().format('YYYY-MM-DD')) {
    return false
  }

  const now = new Date()
  return room.activityInfos.some((activity) => {
    const startTime = new Date(`${currentDate.value} ${activity.startTime.substr(11, 5)}`)
    const endTime = new Date(`${currentDate.value} ${activity.endTime.substr(11, 5)}`)
    return startTime <= now && now <= endTime
  })
}

// 获取会议室列表
const fetchRoomList = async () => {
  loading.value = true
  try {
    const requestParams = {
      roomName: searchParams.value.roomName,
      openStatus: searchParams.value.openStatus,
      positionDescription: searchParams.value.positionDescription,
      date: filterParams.value.date,
    }

    const response = await getListApi(requestParams)
    if (response.code === 0 && response.result) {
      const { rows } = response.result

      // 处理数据中的字段差异
      roomList.value = rows.map((room) => ({
        ...room,
        // 确保活动信息数组存在并格式化时间
        activityInfos: (room.activityInfos || []).map((activity) => ({
          ...activity,
          title: activity.title || '未命名会议',
          startTime: activity.startTime || `${currentDate.value} 00:00:00`,
          endTime: activity.endTime || `${currentDate.value} 23:59:59`,
        })),
      }))

      ElMessage.success('数据加载成功')
    } else {
      console.error('API返回错误:', response)
      ElMessage.error(`获取会议室列表失败: ${response.message || '未知错误'}`)
      roomList.value = []
    }
  } catch (error) {
    console.error('获取会议室列表失败：', error)
    ElMessage.error('网络请求失败，请稍后重试')
    roomList.value = []
  } finally {
    loading.value = false
  }
}

// 处理查看会议室详情
const handleViewRoomDetail = (room: MeetingRoom) => {
  selectedRoom.value = room
  showRoomDetail.value = true
}

// 处理选择会议室
const handleRoomSelect = (room: MeetingRoom) => {
  selectedRoomId.value = room.id
  selectedRoom.value = room
  showRoomDetail.value = true
}

// 处理点击活动
const handleActivityClick = (activity: ActivityInfo) => {
  ElMessage.info(`活动：${activity.title}，时间：${activity.startTime.substr(11, 5)}-${activity.endTime.substr(11, 5)}`)
}

// 处理预约会议室
const handleBookRoom = (room: MeetingRoom) => {
  router.push({
    path: '/home/bookMeeting',
    query: {
      roomId: room.id,
      date: currentDate.value,
    },
  })
}

// 搜索参数
const searchParams = ref({
  roomName: '',
  positionDescription: '',
  openStatus: '',
})

// 会议室位置远程搜索相关状态
const locationOptions = ref<Array<{ label: string; value: string }>>([])
const locationLoading = ref(false)

// 会议室名称远程搜索相关状态
const roomNameOptions = ref<Array<{ label: string; value: string }>>([])
const roomNameLoading = ref(false)

/**
 * 远程搜索会议室位置
 * @param {string} query 用户输入
 */
const remoteLocationSearch = async (query: string) => {
  // 即使是空字符串也继续执行查询
  locationLoading.value = true

  try {
    // 调用后端接口获取位置列表，使用query参数而非路径参数
    const response = await request.get('/api/conferenceRoomManagement/location/list', {
      params: { text: query },
    })
    console.log('位置搜索原始响应:', response)

    // 直接硬编码处理，获取响应中可能包含的数据
    const rawData = (response as any).data?.result || (response as any).result || []
    console.log('位置原始数据:', rawData)

    // 确保是数组并转换为选项格式
    if (Array.isArray(rawData)) {
      locationOptions.value = rawData.map((item: any) => {
        // 如果已经是选项格式
        if (typeof item === 'object' && item !== null && 'label' in item && 'value' in item) {
          return { label: String(item.label), value: String(item.value) }
        }

        // 如果是字符串
        if (typeof item === 'string') {
          return { label: item, value: item }
        }

        // 如果是包含location的对象
        if (typeof item === 'object' && item !== null && 'location' in item) {
          const location = String(item.location)
          return { label: location, value: location }
        }

        // 其他情况
        const strValue = typeof item === 'object' ? JSON.stringify(item) : String(item)
        return { label: strValue, value: strValue }
      })

      console.log('处理后的位置选项:', locationOptions.value)
    } else {
      console.warn('位置数据不是数组')
      locationOptions.value = []
    }
  } catch (error) {
    console.error('获取位置列表失败:', error)
    locationOptions.value = []
  } finally {
    locationLoading.value = false
  }
}

/**
 * 远程搜索会议室名称
 * @param {string} query 用户输入
 */
const remoteRoomNameSearch = async (query: string) => {
  // 即使是空字符串也继续执行查询
  roomNameLoading.value = true

  try {
    // 使用会议室名称专用搜索接口，使用query参数而非路径参数
    const response = await request.get('/api/conferenceRoomManagement/roomName/list', {
      params: {
        text: query,
        location: searchParams.value.positionDescription || '',
      },
    })
    console.log('会议室名称搜索原始响应:', response)

    // 直接硬编码处理，获取响应中可能包含的数据
    const rawData = (response as any).data?.result || (response as any).result || []
    console.log('会议室名称原始数据:', rawData)

    // 确保是数组并转换为选项格式
    if (Array.isArray(rawData)) {
      roomNameOptions.value = rawData.map((item: any) => {
        // 如果已经是选项格式
        if (typeof item === 'object' && item !== null && 'label' in item && 'value' in item) {
          return { label: String(item.label), value: String(item.value) }
        }

        // 如果是字符串
        if (typeof item === 'string') {
          return { label: item, value: item }
        }

        // 优先使用roomName字段
        if (typeof item === 'object' && item !== null && 'roomName' in item) {
          return { label: String(item.roomName), value: String(item.roomName) }
        }

        // 其他情况
        const strValue = typeof item === 'object' ? JSON.stringify(item) : String(item)
        return { label: strValue, value: strValue }
      })

      console.log('处理后的会议室名称选项:', roomNameOptions.value)
    } else {
      console.warn('会议室名称数据不是数组')
      roomNameOptions.value = []
    }
  } catch (error) {
    console.error('获取会议室名称列表失败:', error)
    roomNameOptions.value = []
  } finally {
    roomNameLoading.value = false
  }
}

// 聚焦时加载位置数据
const handleLocationFocus = () => {
  remoteLocationSearch('')
}

// 聚焦时加载会议室名称数据
const handleRoomNameFocus = () => {
  remoteRoomNameSearch('')
}

// 搜索字段配置
const searchFields = ref<Field[]>([
  {
    label: '会议室位置',
    prop: 'positionDescription',
    component: 'select',
    placeholder: '请选择会议室位置',
    componentProps: {
      remote: true,
      // @ts-ignore
      remoteMethod: remoteLocationSearch,
      // @ts-ignore
      loading: locationLoading,
      // @ts-ignore
      options: locationOptions,
      filterable: true,
      clearable: true,
      // 使用focus事件名
      focus: handleLocationFocus,
    },
  },
  {
    label: '会议室名称',
    prop: 'roomName',
    component: 'select',
    placeholder: '请选择会议室名称',
    componentProps: {
      remote: true,
      // @ts-ignore
      remoteMethod: remoteRoomNameSearch,
      // @ts-ignore
      loading: roomNameLoading,
      // @ts-ignore
      options: roomNameOptions,
      filterable: true,
      clearable: true,
      // 使用focus事件名
      focus: handleRoomNameFocus,
    },
  },
  {
    label: '状态',
    prop: 'openStatus',
    component: 'select',
    placeholder: '请选择状态',
    options: Object.values(ROOM_STATUS).map((value) => ({
      label: value,
      value,
    })),
  },
])

// 搜索处理
const handleSearch = () => {
  console.log('搜索参数:', searchParams.value)
  fetchRoomList()
}

// 重置处理
const handleReset = () => {
  searchParams.value = {
    roomName: '',
    positionDescription: '',
    openStatus: '',
  }
  fetchRoomList()
}

// 页面加载时获取会议室列表
onMounted(() => {
  fetchRoomList()
})
</script>

<style scoped>
.meeting-rooms-overview-content {
  height: calc(100vh - 57px);
  padding: 16px;
  overflow-y: auto;
}

.view-toggle-wrapper {
  margin-bottom: 16px;
}

.view-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

@media screen and (max-width: 768px) {
  .view-actions {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
}
</style>
